package gw.com.android.ui.trade;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;

import com.gwtsz.gts2.hx.R;
import com.umeng.analytics.MobclickAgent;

import java.io.IOException;
import java.util.HashMap;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import gw.com.android.app.AppContances;
import gw.com.android.app.AppMain;
import gw.com.android.app.GTConfig;
import gw.com.android.model.ConfigType;
import gw.com.android.model.ConfigUtil;
import gw.com.android.model.DataManager;
import gw.com.android.presenter.http.Https;
import gw.com.android.ui.dialog.ShareDialog;
import gw.com.android.ui.dialog.SharePopWindow;
import gw.com.android.ui.trade.Fragment.BaseOrderFragment;
import gw.com.android.ui.trade.Fragment.MarketOrderCloseFragment;
import gw.com.android.ui.trade.Fragment.OrderFailFragment;
import gw.com.android.ui.trade.Fragment.OrderSucFragment;
import gw.com.jni.library.terminal.GTSConst;
import okhttp3.Request;
import okhttp3.Response;
import www.com.library.app.FragmentsManagerUtil;
import www.com.library.app.Logger;
import www.com.library.model.DataItemDetail;
import www.com.library.util.DoubleConverter;
import www.com.library.util.StringFormatter;
import www.com.library.view.BtnClickListener;
import www.com.library.view.RecyclerClickListener;


/**
 * 持仓界面中平仓操作
 *
 * @author Administrator
 */
public class OrderCloseActivity extends TradeOrderActivity implements PlatformActionListener {

    private MarketOrderCloseFragment mCloseOrderFragment;
    private SharePopWindow mSharePopwindow;
    private DataItemDetail mAccountInfo;

    @Override
    protected void setAcitivityParam() {
        super.setAcitivityParam();
        Intent mIntent = getIntent();
        if (mIntent != null) {
            Bundle bundle = getIntent().getBundleExtra("params");
            mFromType = bundle.getInt("fromType", AppContances.TRADE_TYPE_FORM_QUOTE);
            mUiCode = bundle.getInt("uiCode", 0);
        }
    }

    @Override
    protected void initLayoutView() {
        super.initLayoutView();
        mTitleBar.setAppTitle(R.string.order_type_close_market);
    }

    @Override
    protected void initViewData() {
    }

    /**
     * 返回bundle对象
     */
    private Bundle getBundle() {
        Bundle bundle = getIntent().getBundleExtra("params");
        return bundle;
    }

    /**
     * 展示平仓界面
     */
    public void showOrderFragment() {
        super.showOrderFragment();
        Logger.i("展示平仓界面");
        mTypeTag = AppContances.TAB_ID_CLOSE_ORDER;
        mCurrentTag = AppContances.TAB_ID_CLOSE_ORDER;
        mCloseOrderFragment = (MarketOrderCloseFragment) FragmentsManagerUtil.instance().getFragmentbyTag(this, mCurrentTag);
        if (null == mCloseOrderFragment) {
            mCloseOrderFragment = new MarketOrderCloseFragment();
            mCloseOrderFragment.setArguments(getBundle());
            if (mCloseOrderFragment.mPositionModel == null || mCloseOrderFragment.mUiCode == 0 || mCloseOrderFragment.mSymbolModel == null) {
                Logger.e("平仓mPositionModel对象为空，出现异常" + mUiCode);
                finish();
                return;
            }
            mCloseOrderFragment.setOrderStatusListener(new BaseOrderFragment.onOrderStatusListener() {

                @Override
                public void onSuc(DataItemDetail mDetail) {
                    Logger.i("平仓成功！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！");
                    hasChangeRange = true;
                    GTConfig.instance().saveProductOrderRange(mDetail.getInt("mPrdCode"), mDetail.getString("rangePrice"));
                    mDetailItem.clear().append(mDetail);
                    mHandler.sendEmptyMessage(AppContances.HANDLER_RESULT_SUC);
                }

                @Override
                public void onFail(DataItemDetail mDetail) {
                    Logger.i("平仓失败！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！");
                    //					mDetail.Dump();
                    hasChangeRange = false;
                    mDetailItem.clear().append(mDetail);
                    mHandler.sendEmptyMessage(AppContances.HANDLER_SERVER_FAIL);
                }

                @Override
                public void onFail() {
                    hideLoading();
                }

                @Override
                public void onBegin() {
                    if (mCurrentTag == AppContances.TAB_ID_SUC_ORDER && mCurrentTag == AppContances.TAB_ID_FAILURE_ORDER) {
                        return;
                    }
                    showLoading();
                }

                @Override
                public void onError(String errorMessage) {
                    if (!"".equals(errorMessage) && (mCurrentTag != AppContances.TAB_ID_FAILURE_ORDER && mCurrentTag != AppContances.TAB_ID_SUC_ORDER)) {
                        m_errorTextView.setText(errorMessage);
                        m_errorTextView.setVisibility(View.VISIBLE);
                    } else {
                        m_errorTextView.setVisibility(View.GONE);
                    }
                }

                @Override
                public void onShowView() {
                    mProgressLayout.setVisibility(View.GONE);
                }
            });
            FragmentsManagerUtil.instance().addPushMsgTabFragment(this, mCloseOrderFragment, mCurrentTag);
        }
        showFragment(mCloseOrderFragment);
    }

    /**
     * 展示下单失败界面
     */
    public void showOrderFailFragment(final DataItemDetail mDetail) {
        super.showOrderFailFragment(mDetail);
        Logger.i("展示下单失败界面");
        mCurrentTag = AppContances.TAB_ID_FAILURE_ORDER;
        mFailFragment = (OrderFailFragment) FragmentsManagerUtil.instance().getFragmentbyTag(this, mCurrentTag);
        if (null == mFailFragment) {
            mFailFragment = new OrderFailFragment();
            Bundle bundle = new Bundle();
            bundle.putParcelable("mDetail", mDetail);
            mFailFragment.setArguments(bundle);
            mFailFragment.setBtnClickListener(new BtnClickListener() {

                @Override
                public void onBtnClick(int viewID) {
                    Logger.i("展示平仓界面3333333333");
                    showOrderFragment();
                }
            });
            FragmentsManagerUtil.instance().addPushMsgTabFragment(this, mFailFragment, mCurrentTag);
        } else {
            mFailFragment.setData(mDetail);
        }
        m_errorTextView.setVisibility(View.GONE);
        showFragment(mFailFragment);
    }

    /**
     * 展示下单成功界面
     */
    public void showOrderSucFragment(DataItemDetail mDetail) {
        super.showOrderSucFragment(mDetail);
        mCurrentTag = AppContances.TAB_ID_SUC_ORDER;
        mSucFragment = (OrderSucFragment) FragmentsManagerUtil.instance().getFragmentbyTag(this, mCurrentTag);
        if (null == mSucFragment) {
            mSucFragment = new OrderSucFragment();
            Bundle bundle = new Bundle();
            bundle.putParcelable("mDetail", mDetail);
            mSucFragment.setArguments(bundle);
            FragmentsManagerUtil.instance().addPushMsgTabFragment(this, mSucFragment, mCurrentTag);
        } else {
            mSucFragment.setSucData(mDetail);
        }
        m_errorTextView.setVisibility(View.GONE);
        showFragment(mSucFragment);
    }

    @Override
    public void onSymbolNotify(DataItemDetail tickModel) {
        super.onSymbolNotify(tickModel);
        if (null != mCloseOrderFragment) {
            mCloseOrderFragment.onSymbolNotify(tickModel);
        }
    }

    @Override
    public void onSymbolUpdateNotify() {
        if (null != mCloseOrderFragment) {
            mCloseOrderFragment.onSymbolNotify();
        }
    }

    @Override
    protected void onRightClick() {
        super.onRightClick();
        MobclickAgent.onEvent(this, "shareButton");
        if (null == mSharePopwindow) {
            mSharePopwindow = new SharePopWindow(OrderCloseActivity.this, AppContances.SHARE_ORDER_TYPE, mTitleBar, mDetailItem, new RecyclerClickListener() {
                @Override
                public void onClick(int position, DataItemDetail itemDetail) {
                    mAccountInfo = DataManager.instance().mAccount;
                    double profit = DoubleConverter.add(Double.valueOf(mDetailItem.getString(GTSConst.JSON_KEY_PROFIT)), Double.valueOf(mDetailItem.getString(GTSConst.JSON_KEY_INTEREST)));

                    String shareTitle;
                    String shareCotent;
                    String currency;
                    String mUrl = ConfigUtil.instance().getUrlPath(ConfigType.LOTTERY_SHARE_TAG);
                    if (mAccountInfo.getString(GTSConst.JSON_KEY_TYPE).equals("USD")) {
                        currency = "USD";
                        shareTitle = AppMain.getAppString(R.string.order_share_title, DoubleConverter.to2Decimal(profit) + AppMain.getAppString(R.string.USD_UNIT));
                        shareCotent = AppMain.getAppString(R.string.order_share_content, DoubleConverter.to2Decimal(profit) + AppMain.getAppString(R.string.USD_UNIT));
                    } else if (mAccountInfo.getString(GTSConst.JSON_KEY_TYPE).equals("CNY")) {
                        currency = "CNY";
                        shareTitle = AppMain.getAppString(R.string.order_share_title, DoubleConverter.to2Decimal(profit) + AppMain.getAppString(R.string.CNH_UNIT));
                        shareCotent = AppMain.getAppString(R.string.order_share_content, DoubleConverter.to2Decimal(profit) + AppMain.getAppString(R.string.CNH_UNIT));
                    } else {
                        currency = "";
                        shareTitle = AppMain.getAppString(R.string.order_share_title, DoubleConverter.to2Decimal(profit) + "");
                        shareCotent = AppMain.getAppString(R.string.order_share_content, DoubleConverter.to2Decimal(profit) + "");
                    }
                    mUrl = mUrl + "&profit=" + DoubleConverter.to2Decimal(profit) + "&currency=" + currency;
//					System.out.println("fenxiangUrl:"+mUrl);
                    mSharePopwindow.onShareFun(mSharePopwindow.getTitleId(position), shareTitle, shareCotent, mUrl, OrderCloseActivity.this);
                }
            });
        }
        mSharePopwindow.show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    private Handler mShareHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case AppContances.HANDLER_SHARE_SUCCESS:
//					showToastPopWindow(AppMain.getAppString(R.string.app_share_success));
                    String NowTime = mDetailItem.getString("mTime");
                    String showTime = GTConfig.instance().getStringIsToday(GTConfig.instance().mCurName + GTConfig.PREF_ISSHARED);
                    if (!StringFormatter.IsToday(showTime)) {
                        ShareDialog.showShareDialog(OrderCloseActivity.this, AppMain.getAppString(R.string.app_order_share_success));

                        GTConfig.instance().setStringIsToday(GTConfig.instance().mCurName + GTConfig.PREF_ISSHARED, NowTime);
                        MobclickAgent.onEvent(OrderCloseActivity.this, "firstCloseOrderShare");
                    } else {
                        ShareDialog.showShareDialog(OrderCloseActivity.this, "");
                        MobclickAgent.onEvent(OrderCloseActivity.this, "CloseOrderShare");
                    }
                    uploadShareInfo();
                    break;
                case AppContances.HANDLER_SHARE_CANCEL:
                    showToastPopWindow(AppMain.getAppString(R.string.app_share_cancel));
                    break;
                case AppContances.HANDLER_SHARE_FAIL:
                    showToastPopWindow(AppMain.getAppString(R.string.app_share_fail) + msg.obj);
                    break;
                default:
                    break;
            }
        }

    };

    private void uploadShareInfo() {
        String url = ConfigUtil.instance().getUrlPath(ConfigType.LOTTERY_SHARE_TIMES);
        new Https(url).get(new Https.ResponseCallback<String>() {
            @Override
            public void onSuccess(Request request, Response response, String result, int code) {
                Logger.i("分享返回的数据 成功：" + result);
            }

            @Override
            public void onFailure(Request request, IOException e) {
                Logger.i("分享返回的数据 失败：" + (e == null ? "" : e.getMessage()));
            }
        });
    }

    @Override
    public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
        mShareHandler.sendEmptyMessage(AppContances.HANDLER_SHARE_SUCCESS);
    }

    @Override
    public void onError(Platform platform, int i, Throwable throwable) {
        throwable.printStackTrace();
        Message msg = new Message();
        msg.what = AppContances.HANDLER_SHARE_FAIL;
        msg.obj = throwable.getMessage();
        mShareHandler.sendMessage(msg);
    }

    @Override
    public void onCancel(Platform platform, int i) {
        mShareHandler.sendEmptyMessage(AppContances.HANDLER_SHARE_CANCEL);
    }
}
